#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import random
import string
import argparse

def generate_password(length=12, 
                     use_uppercase=True, 
                     use_lowercase=True, 
                     use_digits=True, 
                     use_symbols=True,
                     exclude_similar=False,
                     exclude_duplicate=False,
                     exclude_space=True):
    """生成一个随机密码"""
    
    # 创建字符集
    chars = ""
    
    if use_uppercase:
        chars += string.ascii_uppercase
    if use_lowercase:
        chars += string.ascii_lowercase
    if use_digits:
        chars += string.digits
    if use_symbols:
        chars += string.punctuation
    if not exclude_space:
        chars += " "
        
    # 排除相似字符
    if exclude_similar:
        for char in "il1Lo0O":
            chars = chars.replace(char, "")
            
    # 验证字符集不为空
    if not chars:
        print("错误：根据您的设置，没有可用的字符")
        return None
        
    # 生成密码
    if exclude_duplicate:
        # 如果排除重复字符，并且长度超过可用字符数量
        if length > len(chars):
            print(f"错误：设置了排除重复字符，但密码长度({length})超过了可用字符数量({len(chars)})")
            return None
        password = ''.join(random.sample(chars, length))
    else:
        password = ''.join(random.choice(chars) for _ in range(length))
    
    # 确保密码包含所选的所有字符类型
    contains_uppercase = any(c in string.ascii_uppercase for c in password) if use_uppercase else True
    contains_lowercase = any(c in string.ascii_lowercase for c in password) if use_lowercase else True
    contains_digit = any(c in string.digits for c in password) if use_digits else True
    contains_symbol = any(c in string.punctuation for c in password) if use_symbols else True
    
    # 如果不满足条件，重新生成
    if not all([contains_uppercase, contains_lowercase, contains_digit, contains_symbol]):
        return generate_password(length, use_uppercase, use_lowercase, use_digits, use_symbols, 
                               exclude_similar, exclude_duplicate, exclude_space)
        
    return password

def evaluate_password_strength(password):
    """评估密码强度"""
    # 简单的密码强度评估
    strength = 0
    
    # 长度得分 (最高 5 分)
    if len(password) >= 8:
        strength += 1
    if len(password) >= 12:
        strength += 1
    if len(password) >= 16:
        strength += 1
    if len(password) >= 20:
        strength += 1
    if len(password) >= 24:
        strength += 1
        
    # 字符类型得分 (每种类型 1 分，最高 4 分)
    if any(c in string.ascii_lowercase for c in password):
        strength += 1
    if any(c in string.ascii_uppercase for c in password):
        strength += 1
    if any(c in string.digits for c in password):
        strength += 1
    if any(c in string.punctuation for c in password):
        strength += 1
        
    # 根据得分设置强度级别
    if strength <= 4:
        return "弱"
    elif strength <= 6:
        return "中等"
    elif strength <= 8:
        return "强"
    else:
        return "非常强"

def main():
    """主函数"""
    parser = argparse.ArgumentParser(description="命令行强密码生成器")
    
    parser.add_argument("-l", "--length", type=int, default=12,
                        help="密码长度 (默认: 12)")
    parser.add_argument("--no-uppercase", action="store_false", dest="uppercase",
                        help="不包含大写字母")
    parser.add_argument("--no-lowercase", action="store_false", dest="lowercase",
                        help="不包含小写字母")
    parser.add_argument("--no-digits", action="store_false", dest="digits",
                        help="不包含数字")
    parser.add_argument("--no-symbols", action="store_false", dest="symbols",
                        help="不包含特殊符号")
    parser.add_argument("--exclude-similar", action="store_true",
                        help="排除相似字符 (i, l, 1, L, o, 0, O)")
    parser.add_argument("--exclude-duplicate", action="store_true",
                        help="排除重复字符")
    parser.add_argument("--include-space", action="store_true",
                        help="包含空格")
    parser.add_argument("-n", "--num-passwords", type=int, default=1,
                        help="生成密码的数量 (默认: 1)")
    
    args = parser.parse_args()
    
    # 检查是否至少启用了一种字符类型
    if not any([args.uppercase, args.lowercase, args.digits, args.symbols]):
        print("错误：至少选择一种字符类型（大写字母、小写字母、数字或特殊符号）")
        return
    
    # 生成指定数量的密码
    for i in range(args.num_passwords):
        password = generate_password(
            length=args.length,
            use_uppercase=args.uppercase,
            use_lowercase=args.lowercase,
            use_digits=args.digits,
            use_symbols=args.symbols,
            exclude_similar=args.exclude_similar,
            exclude_duplicate=args.exclude_duplicate,
            exclude_space=not args.include_space
        )
        
        if password:
            strength = evaluate_password_strength(password)
            print(f"密码 {i+1}: {password} (强度: {strength})")

if __name__ == "__main__":
    main() 